﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;
using NetDon.WebControls;

namespace NetDon.OA.Portal.Finance
{
    [Navigation("干线流程", "营收台帐管理")]

    [Function("eLogistics.RevenueMachineAccountManagement")]
    [PageTabber(Index = 0, NavigateUrl = "~/Finance/RevenueMachineAccountManagement.aspx", Title = "营收台帐管理", Type = typeof(RevenueMachineAccountManagement))]
    [PageTabber(Index = 1, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-StatementOfAccount.aspx", Title = "对帐管理", Type = typeof(RevenueMachineAccountManagement_StatementOfAccount))]
    [PageTabber(Index = 2, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-Invoice.aspx", Title = "开票管理", Type = typeof(RevenueMachineAccountManagement_Invoice))]
    [PageTabber(Index = 3, NavigateUrl = "~/Finance/RevenueMachineAccountManagement-AccountsReceivable.aspx", Title = "收款管理", Type = typeof(RevenueMachineAccountManagement_AccountsReceivable))]


    public partial class RevenueMachineAccountManagement : NavigationPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageQueryAdapter1.PageSize = 20;

                txtReceivingOrderDateStart.Text =
txtConfirmStatementofAccountDateStart.Text =
txtConfirmInvoiceDateStart.Text = txtConfirmAccountsReceiptDateStart.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtReceivingOrderDateEnd.Text =
   txtConfirmStatementofAccountDateEnd.Text =
   txtConfirmInvoiceDateEnd.Text = txtConfirmAccountsReceiptDateEnd.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this.ddlCustomer.InsertEmptyItem(ListEmptyType.Select);

                ddlCompany.InsertEmptyItem(ListEmptyType.Select);
                if (!this.IsSuperRoles())
                {
                    ddlCompany.SelectedValue = CurrentApplicationContext.CompanyId.ToString();
                    ddlCompany.Enabled = false;
                }
                //PageQueryAdapter1.PerformQuery();
            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ObjectDataSourceCustomers.Selecting += (ds, dsArgs) =>
            {
                dsArgs.InputParameters["areaId"] = CurrentApplicationContext.CompanyId.ToString();
            };


        }

        public void ddlCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(ddlCustomer.SelectedValue))
            {

                LoadGoodsShippedTypes(ddlCustomer.SelectedValue.ToGuid());
            }


        }

        private void LoadGoodsShippedTypes(Guid customerId)
        {
            this.ddlGoodsShippedTypeId.Items.Clear();
            this.ddlGoodsShippedTypeId.DataSource = ServiceContainer.GetService<ICustomerInfoService>().GetCustomerGoodsShippTypes(
               customerId, CurrentApplicationContext.CompanyId);
            this.ddlGoodsShippedTypeId.DataBind();
            ddlGoodsShippedTypeId.InsertEmptyItem(ListEmptyType.Select);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.PerformQuery();
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {

            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.DataSource = service.SearchRevenueMachineAccountDataByCondition((RevenueMachineAccountSearchCriteria)e.Condition, gridOrderList.SortExpression,
                                                      gridOrderList.SortDirection, e.PageSize, e.PageIndex);

        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            e.RecordCount = service.GetRevenueMachineAccountsCount((RevenueMachineAccountSearchCriteria)e.Condition);
        }

        protected void PageQueryAdapter1_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var criteria = new RevenueMachineAccountSearchCriteria
            {
               
            };
            if (!MiscUtilities.IsNullOrEmpty(ddlCompany.SelectedValue))
            {
                criteria.AreaId = ddlCompany.SelectedValue.ToGuid();
            }




            if (!string.IsNullOrEmpty(txtOrderCode.Text))
            {
                criteria.OrderCode = txtOrderCode.Text.Trim();
            }

            if (!string.IsNullOrEmpty(txtTransportationPlanCode.Text))
            {
                criteria.TransportationPlanCode = txtTransportationPlanCode.Text.Trim();
            }
            DateTime? dateStart = null, dateEnd = null;
            if (!string.IsNullOrEmpty(txtReceiptInfoActualResponseDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceiptInfoActualResponseDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceiptInfoActualResponseDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceiptInfoActualResponseDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceiptInfoActualResponseDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (radioIsStatementofAccountNeededYes.Checked)
            {
                criteria.IsStatementofAccountCompleted = true;

                dateStart = null; dateEnd = null;
                if (!string.IsNullOrEmpty(txtConfirmStatementofAccountDateStart.Text.Trim()))
                {
                    dateStart = DateTime.Parse(txtConfirmStatementofAccountDateStart.Text.Trim());
                }
                if (!string.IsNullOrEmpty(txtConfirmStatementofAccountDateEnd.Text.Trim()))
                {
                    dateEnd = DateTime.Parse(txtConfirmStatementofAccountDateEnd.Text.Trim());
                }
                if ((dateStart.HasValue || dateEnd.HasValue) && radioIsStatementofAccountNeededYes.Checked)
                {
                    criteria.ConfirmStatementofAccountDate = new Range<DateTime?>(dateStart, dateEnd);
                }
            }
            else if (radioIsStatementofAccountNeededNo.Checked)
            {
                criteria.IsStatementofAccountCompleted = false;
            }


            if (radioIsInvoiceNeededYes.Checked)
            {
                criteria.IsInvoiced = true;
                dateStart = null; dateEnd = null;
                if (!string.IsNullOrEmpty(txtConfirmInvoiceDateStart.Text.Trim()))
                {
                    dateStart = DateTime.Parse(txtConfirmInvoiceDateStart.Text.Trim());
                }
                if (!string.IsNullOrEmpty(txtConfirmInvoiceDateEnd.Text.Trim()))
                {
                    dateEnd = DateTime.Parse(txtConfirmInvoiceDateEnd.Text.Trim());
                }
                if ((dateStart.HasValue || dateEnd.HasValue) && radioIsInvoiceNeededYes.Checked)
                {
                    criteria.ConfirmInvoiceDate = new Range<DateTime?>(dateStart, dateEnd);
                }

            }
            else if (radioIsInvoiceNeededNo.Checked)
            {
                criteria.IsInvoiced = false;
            }


            if (radioIsAccountsReceivableYes.Checked)
            {
                criteria.IsAccountsReceivable = true;
                dateStart = null; dateEnd = null;
                if (!string.IsNullOrEmpty(txtConfirmAccountsReceiptDateStart.Text.Trim()))
                {
                    dateStart = DateTime.Parse(txtConfirmAccountsReceiptDateStart.Text.Trim());
                }
                if (!string.IsNullOrEmpty(txtConfirmInvoiceDateEnd.Text.Trim()))
                {
                    dateEnd = DateTime.Parse(txtConfirmInvoiceDateEnd.Text.Trim());
                }
                if ((dateStart.HasValue || dateEnd.HasValue) && radioIsAccountsReceivableYes.Checked)
                {
                    criteria.ConfirmAccountsReceiptDate = new Range<DateTime?>(dateStart, dateEnd);
                }

            }
            else if (radioIsAccountsReceivableNo.Checked)
            {
                criteria.IsAccountsReceivable = false;
            }

            dateStart = null; dateEnd = null;
            if (!string.IsNullOrEmpty(txtReceivingOrderDateStart.Text.Trim()))
            {
                dateStart = DateTime.Parse(txtReceivingOrderDateStart.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtReceivingOrderDateEnd.Text.Trim()))
            {
                dateEnd = DateTime.Parse(txtReceivingOrderDateEnd.Text.Trim());
            }
            if (dateStart.HasValue || dateEnd.HasValue)
            {
                criteria.ReceivingOrderDate = new Range<DateTime?>(dateStart, dateEnd);
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlRouteTypeId.SelectedValue.ToGuid()))
            {
                criteria.RouteTypeId = ddlRouteTypeId.SelectedValue.ToGuid();
            }
            if (!string.IsNullOrEmpty(ddlGoodsShippedTypeId.SelectedValue))
            {
                criteria.GoodsShippedTypeId = ddlGoodsShippedTypeId.SelectedValue.ToGuid();
            }

            if (!MiscUtilities.IsNullOrEmpty(ddlCustomer.SelectedValue.ToGuid()))
            {
                criteria.CustomerId = ddlCustomer.SelectedValue.ToGuid();
            }

            e.Condition = criteria;
        }

        protected void btnReload_Click(object sender, EventArgs e)
        {
            PageQueryAdapter1.ReloadCurrentPage();
        }

        protected void gridOrderList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var entity = (e.Row.DataItem);

                var orderId = e.Row.Attributes["Id"] = Convert.ToString(DataBinder.Eval(entity, "Id"));
                var isStatementofAccountCompleted = Convert.ToBoolean(DataBinder.Eval(entity,"IsStatementofAccountCompleted"));
                e.Row.Attributes["IsStatementofAccountCompleted"] = isStatementofAccountCompleted.ToString();

                var isInvoiced = Convert.ToBoolean(DataBinder.Eval(entity, "IsInvoiced"));
                e.Row.Attributes["IsInvoiced"] = isInvoiced.ToString();

                var isAccountsReceivable = Convert.ToBoolean(DataBinder.Eval(entity, "IsAccountsReceivable"));
                e.Row.Attributes["IsAccountsReceivable"] = isAccountsReceivable.ToString();

                var btnEdit = (ImageButton)e.Row.FindControl("btnEdit");
                if (btnEdit != null)
                {
                    btnEdit.OnClientClick = string.Format("modifyOrder('{0}','{1}');return false;", orderId, isStatementofAccountCompleted || isInvoiced || isAccountsReceivable ? "true" : "false");
                }
                if (!MiscUtilities.IsNullOrEmpty(DataBinder.Eval(entity, "ProfitRate")) && Convert.ToDecimal(DataBinder.Eval(entity, "ProfitRate")) < 0)
                {
                    e.Row.Style.Add("background-color", "#FF6600");

                }
                //var btnConfirm = (ImageButton)e.Row.FindControl("btnConfirm");
                //if (btnConfirm != null)
                //{
                //    btnConfirm.OnClientClick = string.Format("modifyOrder('{0}');return false;", orderId);
                //}
            }
        }


        protected decimal GetProfitRate(object profit, object totalRevenues)
        {
            if (MiscUtilities.IsNullOrEmpty(totalRevenues)) return 0;
            if (MiscUtilities.IsNullOrEmpty(profit)) return 0;
            if (totalRevenues.ToString().ToDecimal() == 0) return 0;
            return Math.Round(((profit.ToString().ToDecimal() / totalRevenues.ToString().ToDecimal() ?? 0) * 100), 2);

        }
        protected void radioIsAccountsReceivable_CheckedChanged(object sender, EventArgs e)
         {
            
            var radioButton = (sender as RadioButton);
            if (radioButton.Checked)
            {
                if (radioButton.ID == "radioIsAccountsReceivableAll")
                {
                    this.txtConfirmAccountsReceiptDateEnd.Enabled =
                        this.txtConfirmAccountsReceiptDateStart.Enabled = this.txtConfirmAccountsReceiptDateEnd.Visible =
                        this.txtConfirmAccountsReceiptDateStart.Visible = Label4.Visible = false;
                }
                if (radioButton.ID == "radioIsAccountsReceivableYes")
                {
                    this.txtConfirmAccountsReceiptDateEnd.Enabled =
                        this.txtConfirmAccountsReceiptDateStart.Enabled = this.txtConfirmAccountsReceiptDateEnd.Visible =
                        this.txtConfirmAccountsReceiptDateStart.Visible = Label4.Visible = true;
                }
                if (radioButton.ID == "radioIsAccountsReceivableNo")
                {
                    this.txtConfirmAccountsReceiptDateEnd.Enabled =
                       this.txtConfirmAccountsReceiptDateStart.Enabled = this.txtConfirmAccountsReceiptDateEnd.Visible =
                       this.txtConfirmAccountsReceiptDateStart.Visible = Label4.Visible = false;
                }
            }
         }

        protected void radioIsInvoiceNeeded_CheckedChanged(object sender, EventArgs e)
        {

            var radioButton = (sender as RadioButton);
            if (radioButton.Checked)
            {
                if (radioButton.ID == "radioIsInvoiceNeededAll")
                {
                    this.txtConfirmInvoiceDateStart.Enabled =
                        this.txtConfirmInvoiceDateEnd.Enabled = this.txtConfirmInvoiceDateStart.Visible =
                        this.txtConfirmInvoiceDateEnd.Visible = Label3.Visible = false;
                }
                if (radioButton.ID == "radioIsInvoiceNeededYes")
                {
                    this.txtConfirmInvoiceDateStart.Enabled =
                      this.txtConfirmInvoiceDateEnd.Enabled = this.txtConfirmInvoiceDateStart.Visible =
                      this.txtConfirmInvoiceDateEnd.Visible = Label3.Visible = true;
                }
                if (radioButton.ID == "radioIsInvoiceNeededNo")
                {
                    this.txtConfirmInvoiceDateStart.Enabled =
                       this.txtConfirmInvoiceDateEnd.Enabled = this.txtConfirmInvoiceDateStart.Visible =
                       this.txtConfirmInvoiceDateEnd.Visible = Label3.Visible = false;
                }
            }
        }
        protected void radioIsStatementofAccountNeeded_CheckedChanged(object sender, EventArgs e)
        {

            var radioButton = (sender as RadioButton);
            if (radioButton.Checked)
            {
                if (radioButton.ID == "radioIsStatementofAccountNeededAll")
                {
                    this.txtConfirmStatementofAccountDateEnd.Enabled =
                        this.txtConfirmStatementofAccountDateStart.Enabled = this.txtConfirmStatementofAccountDateEnd.Visible =
                        this.txtConfirmStatementofAccountDateStart.Visible = Label2.Visible = false;
                }
                if (radioButton.ID == "radioIsStatementofAccountNeededYes")
                {
                    this.txtConfirmStatementofAccountDateEnd.Enabled =
                        this.txtConfirmStatementofAccountDateStart.Enabled = this.txtConfirmStatementofAccountDateEnd.Visible =
                        this.txtConfirmStatementofAccountDateStart.Visible = Label2.Visible = true;
                }
                if (radioButton.ID == "radioIsStatementofAccountNeededNo")
                {
                    this.txtConfirmStatementofAccountDateEnd.Enabled =
                         this.txtConfirmStatementofAccountDateStart.Enabled = this.txtConfirmStatementofAccountDateEnd.Visible =
                         this.txtConfirmStatementofAccountDateStart.Visible = Label2.Visible = false;
                }
            }
        }
        


        
    }
}